package com.pmcc.cj.service;

import com.pmcc.cj.entity.CjCommodityYun;
import com.pmcc.cj.entity.CjCommodityYunDetail;
import com.pmcc.cj.entity.vo.NameVo;
import com.pmcc.cj.repository.CjCommodityYunDetailRepository;
import com.pmcc.cj.repository.CjCommodityYunRepository;
import com.pmcc.cj.vo.CommodityYunVo;
import com.pmcc.cj.vo.GoodsVo;
import com.pmcc.core.entity.Dict;
import com.pmcc.core.repository.DictRepository;
import com.pmcc.utils.AntdPage;
import com.pmcc.utils.BeanUtils;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by tomas on 2020/9/24.
 */
@Transactional
@Service
public class CjCommodityYunService {
    @Autowired
    CjCommodityYunRepository cjCommodityYunRepository;
    @Autowired
    DictRepository dictRepository;
    @Autowired
    CjCommodityYunDetailRepository cjCommodityYunDetailRepository;

    public ResultBean queryCommodityYunByPage(CjCommodityYun model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            if(StringUtil.isEmpty(model.getProductId()) || StringUtil.isEmpty(model.getTypeId())) return resultBean;
            Page page = cjCommodityYunRepository.findAll(this.getCommodityYunSpecification(model), antdPage.getPageRequest());
            if(page != null && page.getContent().size()>0){
                for(CjCommodityYun cjCommodityYun: (List<CjCommodityYun>)page.getContent()){
                    List<CjCommodityYunDetail> list = cjCommodityYunDetailRepository.findByCommodityYunId(cjCommodityYun.getId());
                    if(list != null && list.size()>0){
                        for(CjCommodityYunDetail detail : list){
                            detail.setProductId(cjCommodityYun.getProductId());
                            detail.setTypeId(cjCommodityYun.getTypeId());
                            detail.setName(cjCommodityYun.getName());
                        }
                    }
                    cjCommodityYun.setDetails(list);
                }
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjCommodityYun> getCommodityYunSpecification(CjCommodityYun model) {
        return new Specification<CjCommodityYun>() {
            @Override
            public Predicate toPredicate(Root<CjCommodityYun> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                //商品分类
                if(StringUtil.isNotEmpty(model.getProductId())){
                    list.add(builder.equal(root.get("productId").as(String.class),  model.getProductId()));
                }
                //功能分类
                if(StringUtil.isNotEmpty(model.getTypeId())){
                    list.add(builder.equal(root.get("typeId").as(String.class),  model.getTypeId()));
                }
                if(model.getIsDashboard()!= null){
                    list.add(builder.equal(root.get("isDashboard").as(Integer.class), model.getIsDashboard()));
                }
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean commodityYunDict(String code){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<Dict> list= new ArrayList<>();
            List<Dict> ll=dictRepository.findByCode(code);
            if(ll != null && ll.size()>0){
                list=dictRepository.findByParentIdAndDelFlagOrderBySequenceAsc(ll.get(0).getId(),"0");
            }
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean addCommodityYun(CjCommodityYun model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            model.setScore(0);
            cjCommodityYunRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean addCommodityYunDetail(CjCommodityYunDetail model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            cjCommodityYunDetailRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean deleteCommodityYun(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            //先删除子表
            cjCommodityYunDetailRepository.deleteByCommodityYunId(id);
            cjCommodityYunRepository.delete(id);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean deleteCommodityYunDetail(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            cjCommodityYunDetailRepository.delete(id);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean modifyCommodityYun(Map map){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCommodityYun c = cjCommodityYunRepository.findOne(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            cjCommodityYunRepository.saveAndFlush(c);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean modifyCommodityYunDetail(Map map){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCommodityYunDetail c = cjCommodityYunDetailRepository.findOne(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            cjCommodityYunDetailRepository.saveAndFlush(c);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean queryCommodityYun(String productId,String typeId) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjCommodityYun> list=cjCommodityYunRepository.findByProductIdAndTypeIdAndFettle(productId,typeId,0);
            List<CommodityYunVo> alist=new ArrayList<>();
            for(CjCommodityYun cy:list){
                CommodityYunVo cv=new CommodityYunVo(cy.getId(),cy.getName(),cy.getPrice(),cy.getAddress());
                alist.add(cv);
            }
            resultBean.setRows(alist);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;

    }

    public ResultBean queryRecommendByPage(AntdPage antdPage) {

        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCommodityYun model=new CjCommodityYun();
            model.setIsDashboard(1);
            Page page = cjCommodityYunRepository.findAll(this.getCommodityYunSpecification(model), antdPage.getPageRequest());
            List<GoodsVo> list=new ArrayList<>();
            if(page != null && page.getContent().size()>0){
                for(CjCommodityYun ccy: (List<CjCommodityYun>)page.getContent()){
                    GoodsVo gv=new GoodsVo(ccy.getId(),ccy.getName(),ccy.getPrice(),ccy.getAddress());
                    gv.setType("云飞防");
                    gv.setNums(ccy.getScore());
                    list.add(gv);

                }
                //以后这里添加云商城的，并且加完之后做乱序排列
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean getCommodityDetail(String id,String type){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CommodityYunVo commodityYunVo  = new CommodityYunVo();
            if("云商城".equals(type)){

            }else if("云飞防".equals(type)){
                CjCommodityYun commodityYun = cjCommodityYunRepository.findOne(id);
                if(commodityYun != null){
                    BeanUtils.copyProperties(commodityYun,commodityYunVo);
                    List<CjCommodityYunDetail> list = cjCommodityYunDetailRepository.findByCommodityYunId(id);
                    commodityYunVo.setChildren(list);
                }
            }
            resultBean.setObject(commodityYunVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean getCropName(String dictId){
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            List<NameVo> lt = new ArrayList<>();
            List list = cjCommodityYunRepository.queryCountryCombo(dictId);
            if(list!= null && list.size()>0){
                for(Object object : list){
                    NameVo nameVo = new NameVo();
                    nameVo.setId(((Object[])object)[0].toString());
                    nameVo.setName(((Object[])object)[1].toString());
                    lt.add(nameVo);
                }
            }
            resultBean.setRows(lt);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean detailRelated(String id,String yunId){
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjCommodityYunDetail> lt = new ArrayList<>();
            List<CjCommodityYunDetail> list = cjCommodityYunDetailRepository.findByCommodityYunId(yunId);
            if(list != null && list.size()>0){
                for(CjCommodityYunDetail commodityYunDetail : list){
                    if(id.equals(commodityYunDetail.getId())){
                        continue;
                    }
                    lt.add(commodityYunDetail);
                }
            }
            resultBean.setRows(lt);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean detailRelatedConfirm(String id,String relateId){
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            CjCommodityYunDetail commodityYunDetail=cjCommodityYunDetailRepository.findOne(relateId);
            CjCommodityYunDetail cjCommodityYunDetail=cjCommodityYunDetailRepository.findOne(id);
            cjCommodityYunDetail.setRelateId(relateId);
            cjCommodityYunDetail.setRelateName(commodityYunDetail.getDetailName());
            cjCommodityYunDetailRepository.saveAndFlush(cjCommodityYunDetail);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
